Explain the difference between checked and unchecked exceptions. Provide examples.
Explain the difference between checked and unchecked exceptions. Provide examples.
388
18-Jul-2024
Ravi Vishwakarma
18-Jul-2024In Java, exceptions are categorized into two main types: checked exceptions and unchecked exceptions. Understanding their differences is crucial for handling errors effectively in your code.
Checked Exceptions
Checked exceptions are the exceptions that are checked at compile-time. This means the compiler checks that these exceptions are caught or declared to be thrown in the method signature using
throws
keyword.Usage: Typically used to indicate conditions that a well-behaved application should anticipate and handle. Examples include I/O errors, database connection issues, and file not found situations.
Examples:
IOException
SQLException
FileNotFoundException
Example Code:
In this example,
IOException
is a checked exception that occurs when handling file operations like reading from a file. It must be caught or declared in the method signature usingthrows
.Unchecked Exceptions (Runtime Exceptions)
Unchecked exceptions are exceptions that are not checked at compile-time. They occur at runtime and do not need to be explicitly handled or declared using
throws
.Usage: Typically caused by programming bugs, such as accessing an array out of bounds or attempting to perform arithmetic division by zero. These are usually unexpected conditions and may indicate logic errors in the code.
Examples:
NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
Example Code:
In this example,
ArithmeticException
is an unchecked exception that occurs when attempting to divide by zero (divisor = 0
). It does not need to be explicitly handled withthrows
.Key Differences
throws
)IOException
,SQLException
NullPointerException
,ArrayIndexOutOfBoundsException
Summary
throws
, used for recoverable conditions.Understanding these distinctions helps in designing robust error-handling mechanisms in Java applications, ensuring proper handling of both anticipated and unforeseen exceptions.
Read more
What is the purpose of the volatile keyword in Java?
What are annotations in Java? How are they used?
Describe the life cycle of a thread in Java.